import { DIContainer } from '../../infrastructure/di';
import { UnifiedServiceRegistry } from './UnifiedServiceRegistry';
import { IGameService } from './IGameService';

/**
 * 服务迁移计划和工具
 * 帮助现有服务逐步迁移到新的统一架构
 */

/**
 * 迁移阶段枚举
 */
export enum MigrationPhase {
    /** 准备阶段 - 创建新服务但不启用 */
    PREPARATION = 'preparation',
    /** 双写阶段 - 新旧服务并行运行 */
    DUAL_WRITE = 'dual_write',
    /** 测试阶段 - 部分流量切换到新服务 */
    TESTING = 'testing',
    /** 切换阶段 - 完全切换到新服务 */
    SWITCHING = 'switching',
    /** 清理阶段 - 移除旧服务 */
    CLEANUP = 'cleanup',
    /** 完成阶段 - 迁移完成 */
    COMPLETED = 'completed'
}

/**
 * 迁移配置
 */
interface MigrationConfig {
    /** 服务名称 */
    serviceName: string;
    /** 旧服务标识 */
    legacyServiceName: string;
    /** 新服务标识 */
    modernServiceName: string;
    /** 当前迁移阶段 */
    currentPhase: MigrationPhase;
    /** 流量分配百分比（新服务） */
    trafficPercentage: number;
    /** 是否启用回滚 */
    enableRollback: boolean;
    /** 迁移开始时间 */
    migrationStartTime: number;
    /** 预计完成时间 */
    estimatedCompletionTime: number;
}

/**
 * 迁移状态监控
 */
interface MigrationStatus {
    config: MigrationConfig;
    /** 成功调用次数 */
    successCount: number;
    /** 失败调用次数 */
    errorCount: number;
    /** 平均响应时间 */
    avgResponseTime: number;
    /** 最后更新时间 */
    lastUpdateTime: number;
    /** 错误详情 */
    recentErrors: Array<{
        timestamp: number;
        method: string;
        error: string;
    }>;
}

/**
 * 服务迁移管理器
 */
export class ServiceMigrationManager {
    private static instance: ServiceMigrationManager;
    private registry: UnifiedServiceRegistry;
    private migrations = new Map<string, MigrationStatus>();
    private rollbackHandlers = new Map<string, () => Promise<void>>();

    private constructor(registry: UnifiedServiceRegistry) {
        this.registry = registry;
    }

    static getInstance(registry: UnifiedServiceRegistry): ServiceMigrationManager {
        if (!this.instance) {
            this.instance = new ServiceMigrationManager(registry);
        }
        return this.instance;
    }

    /**
     * 开始服务迁移
     */
    startMigration(config: MigrationConfig): void {
        const status: MigrationStatus = {
            config,
            successCount: 0,
            errorCount: 0,
            avgResponseTime: 0,
            lastUpdateTime: Date.now(),
            recentErrors: []
        };

        this.migrations.set(config.serviceName, status);
        console.log(`🚀 Started migration for service: ${config.serviceName}`);
        console.log(`Phase: ${config.currentPhase}, Traffic: ${config.trafficPercentage}%`);
    }

    /**
     * 更新迁移阶段
     */
    updateMigrationPhase(serviceName: string, phase: MigrationPhase, trafficPercentage?: number): void {
        const status = this.migrations.get(serviceName);
        if (!status) {
            throw new Error(`Migration not found for service: ${serviceName}`);
        }

        status.config.currentPhase = phase;
        if (trafficPercentage !== undefined) {
            status.config.trafficPercentage = trafficPercentage;
        }
        status.lastUpdateTime = Date.now();

        console.log(`📈 Updated migration phase for ${serviceName}: ${phase} (${status.config.trafficPercentage}%)`);
    }

    /**
     * 记录迁移调用结果
     */
    recordMigrationCall(serviceName: string, method: string, success: boolean, responseTime: number, error?: Error): void {
        const status = this.migrations.get(serviceName);
        if (!status) {
            return;
        }

        if (success) {
            status.successCount++;
        } else {
            status.errorCount++;
            if (error) {
                status.recentErrors.push({
                    timestamp: Date.now(),
                    method,
                    error: error.message
                });
                // 保持最近20个错误
                if (status.recentErrors.length > 20) {
                    status.recentErrors.shift();
                }
            }
        }

        // 更新平均响应时间
        const totalCalls = status.successCount + status.errorCount;
        status.avgResponseTime = (status.avgResponseTime * (totalCalls - 1) + responseTime) / totalCalls;
        status.lastUpdateTime = Date.now();

        // 检查错误率，如果过高自动回滚
        const errorRate = status.errorCount / totalCalls;
        if (errorRate > 0.1 && totalCalls > 10) { // 错误率超过10%且调用次数超过10次
            console.warn(`⚠️ High error rate detected for ${serviceName}: ${(errorRate * 100).toFixed(2)}%`);
            if (status.config.enableRollback) {
                this.triggerRollback(serviceName, `High error rate: ${(errorRate * 100).toFixed(2)}%`);
            }
        }
    }

    /**
     * 触发回滚
     */
    async triggerRollback(serviceName: string, reason: string): Promise<void> {
        console.warn(`🔄 Triggering rollback for ${serviceName}: ${reason}`);
        
        const status = this.migrations.get(serviceName);
        if (status) {
            // 切换回旧服务
            status.config.trafficPercentage = 0;
            status.config.currentPhase = MigrationPhase.PREPARATION;
        }

        // 执行自定义回滚处理器
        const rollbackHandler = this.rollbackHandlers.get(serviceName);
        if (rollbackHandler) {
            try {
                await rollbackHandler();
                console.log(`✅ Rollback completed for ${serviceName}`);
            } catch (error) {
                console.error(`❌ Rollback failed for ${serviceName}:`, error);
            }
        }
    }

    /**
     * 注册回滚处理器
     */
    registerRollbackHandler(serviceName: string, handler: () => Promise<void>): void {
        this.rollbackHandlers.set(serviceName, handler);
    }

    /**
     * 获取迁移状态
     */
    getMigrationStatus(serviceName: string): MigrationStatus | undefined {
        return this.migrations.get(serviceName);
    }

    /**
     * 获取所有迁移状态
     */
    getAllMigrationStatus(): Map<string, MigrationStatus> {
        return new Map(this.migrations);
    }

    /**
     * 完成迁移
     */
    completeMigration(serviceName: string): void {
        const status = this.migrations.get(serviceName);
        if (!status) {
            throw new Error(`Migration not found for service: ${serviceName}`);
        }

        status.config.currentPhase = MigrationPhase.COMPLETED;
        status.config.trafficPercentage = 100;
        status.lastUpdateTime = Date.now();

        console.log(`🎉 Migration completed for service: ${serviceName}`);
        
        // 清理回滚处理器
        this.rollbackHandlers.delete(serviceName);
    }

    /**
     * 生成迁移报告
     */
    generateMigrationReport(): string {
        let report = '# 服务迁移状态报告\n\n';
        report += `生成时间: ${new Date().toISOString()}\n\n`;
        
        for (const [serviceName, status] of this.migrations.entries()) {
            const totalCalls = status.successCount + status.errorCount;
            const errorRate = totalCalls > 0 ? (status.errorCount / totalCalls * 100).toFixed(2) : '0.00';
            const successRate = totalCalls > 0 ? (status.successCount / totalCalls * 100).toFixed(2) : '0.00';
            
            report += `## ${serviceName}\n`;
            report += `- **阶段**: ${status.config.currentPhase}\n`;
            report += `- **流量分配**: ${status.config.trafficPercentage}%\n`;
            report += `- **成功率**: ${successRate}%\n`;
            report += `- **错误率**: ${errorRate}%\n`;
            report += `- **平均响应时间**: ${status.avgResponseTime.toFixed(2)}ms\n`;
            report += `- **总调用次数**: ${totalCalls}\n`;
            
            if (status.recentErrors.length > 0) {
                report += `- **最近错误** (最多显示5个):\n`;
                status.recentErrors.slice(-5).forEach(error => {
                    report += `  - ${new Date(error.timestamp).toISOString()}: ${error.method} - ${error.error}\n`;
                });
            }
            
            report += '\n';
        }
        
        return report;
    }
}

/**
 * 迁移代理服务
 * 用于在迁移期间智能路由请求到新旧服务
 */
export class MigrationProxyService<T> {
    private migrationManager: ServiceMigrationManager;
    private serviceName: string;
    
    constructor(
        private legacyService: T,
        private modernService: T,
        serviceName: string,
        migrationManager: ServiceMigrationManager
    ) {
        this.serviceName = serviceName;
        this.migrationManager = migrationManager;
    }

    /**
     * 代理方法调用
     */
    async proxyCall<K extends keyof T>(
        method: K,
        ...args: T[K] extends (...args: any[]) => any ? Parameters<T[K]> : never
    ): Promise<any> {
        const status = this.migrationManager.getMigrationStatus(this.serviceName);
        if (!status) {
            // 没有迁移配置，使用旧服务
            return (this.legacyService[method] as any)(...args);
        }

        const startTime = Date.now();
        const shouldUseModern = this.shouldUseModernService(status);
        
        try {
            let result;
            if (shouldUseModern) {
                result = await (this.modernService[method] as any)(...args);
            } else {
                result = await (this.legacyService[method] as any)(...args);
            }
            
            const responseTime = Date.now() - startTime;
            this.migrationManager.recordMigrationCall(
                this.serviceName, 
                method as string, 
                true, 
                responseTime
            );
            
            return result;
        } catch (error) {
            const responseTime = Date.now() - startTime;
            this.migrationManager.recordMigrationCall(
                this.serviceName, 
                method as string, 
                false, 
                responseTime, 
                error as Error
            );
            
            // 如果现代服务失败，尝试降级到旧服务
            if (shouldUseModern) {
                console.warn(`Modern service failed, falling back to legacy: ${(error as Error).message}`);
                try {
                    return await (this.legacyService[method] as any)(...args);
                } catch (fallbackError) {
                    throw fallbackError;
                }
            }
            
            throw error;
        }
    }

    /**
     * 判断是否应该使用现代服务
     */
    private shouldUseModernService(status: MigrationStatus): boolean {
        // 如果不在测试阶段以上，不使用现代服务
        if (status.config.currentPhase === MigrationPhase.PREPARATION || 
            status.config.currentPhase === MigrationPhase.DUAL_WRITE) {
            return false;
        }
        
        // 如果流量分配为0，不使用现代服务
        if (status.config.trafficPercentage === 0) {
            return false;
        }
        
        // 如果流量分配为100%，使用现代服务
        if (status.config.trafficPercentage >= 100) {
            return true;
        }
        
        // 根据流量分配百分比随机决定
        return Math.random() * 100 < status.config.trafficPercentage;
    }
}

/**
 * 预设的迁移计划
 */
export const MIGRATION_PLANS = {
    BAG_SERVICE: {
        serviceName: 'BagService',
        legacyServiceName: 'BagService',
        modernServiceName: 'UnifiedBagService',
        currentPhase: MigrationPhase.PREPARATION,
        trafficPercentage: 0,
        enableRollback: true,
        migrationStartTime: Date.now(),
        estimatedCompletionTime: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天后
    } as MigrationConfig,
    
    RPG_SERVICE: {
        serviceName: 'RPGService',
        legacyServiceName: 'RPGService',
        modernServiceName: 'UnifiedRPGService',
        currentPhase: MigrationPhase.PREPARATION,
        trafficPercentage: 0,
        enableRollback: true,
        migrationStartTime: Date.now(),
        estimatedCompletionTime: Date.now() + 14 * 24 * 60 * 60 * 1000 // 14天后
    } as MigrationConfig,
    
    TALENT_SERVICE: {
        serviceName: 'TalentService',
        legacyServiceName: 'TalentService',
        modernServiceName: 'UnifiedTalentService',
        currentPhase: MigrationPhase.PREPARATION,
        trafficPercentage: 0,
        enableRollback: true,
        migrationStartTime: Date.now(),
        estimatedCompletionTime: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天后
    } as MigrationConfig
};
